//
//  UIImage+instancetype.m
//  CoreCode
//
//  Created by 曹连华 on 2020/6/4.
//


#import "UIImage+instance.h"

@implementation UIImage (instance)

+ (UIImage*)imageWithFileName:(NSString *)name bundleName:(NSString *)bundleName aClass:(Class)aClass {
    return [UIImage imageWithFileName:name bundleName:bundleName aClass:aClass extension:@"png"];
}

+ (UIImage*)imageWithFileName:(NSString *)name
                   bundleName:(NSString *)bundleName
                       aClass:(Class)aClass
                    extension:(NSString *)extension {
    NSArray * components = [name componentsSeparatedByString:@"."];
    if ([components count] >= 2) {
        NSUInteger lastIndex = components.count - 1;
        extension = [components objectAtIndex:lastIndex];
        name = [name substringToIndex:(name.length - (extension.length + 1))];
    }
    NSString * path = @"";
    // 如果为Retina屏幕且存在对应图片，则返回Retina图片，否则查找普通图片
    if ([UIScreen mainScreen].scale == 2.0
        || [UIScreen mainScreen].scale == 3.0) {
        name = [name stringByAppendingString:[NSString stringWithFormat:@"@%dx",(int)[UIScreen mainScreen].scale]];
        
        NSURL * url = [[NSBundle bundleForClass:aClass] URLForResource:[NSString stringWithFormat:@"%@.bundle",bundleName] withExtension:nil];
        NSBundle * bundle = [NSBundle bundleWithURL:url];
        path = [bundle pathForResource:name ofType:extension];
    }
    
    if (path != nil) {
        return [UIImage imageWithContentsOfFile:path];
    }
    return nil;
    
}

+ (UIImage *)imageWithColor:(UIColor *)aColor {
    return [self imageWithColor:aColor cornerRadius:0 size:CGSizeMake(1.0f, 1.0f)];
}

+ (UIImage *)imageWithColor:(UIColor *)aColor cornerRadius:(CGFloat)cornerRadius {
    CGFloat minSize = cornerRadius * 2 + 1;
    return [self imageWithColor:aColor cornerRadius:cornerRadius size:CGSizeMake(minSize, minSize)];
}

+ (UIImage *)imageWithColor:(UIColor *)aColor cornerRadius:(CGFloat)cornerRadius size:(CGSize)size {
    if (cornerRadius) {
        CGFloat minSize = cornerRadius * 2 + 1;
        if (size.width < minSize) {
            size.width = minSize;
        }
        
        if (size.height < minSize) {
            size.height = minSize;
        }
    }
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [aColor CGColor]);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    if (cornerRadius) {
        UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
        roundedRect.lineWidth = 0;
        [roundedRect fill];
    } else {
        CGContextFillRect(context, rect);
    }
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    if (cornerRadius) {
        theImage = [theImage resizableImageWithCapInsets:UIEdgeInsetsMake(cornerRadius, cornerRadius, cornerRadius, cornerRadius)];
    }
    return theImage;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (UIImage *)imageWithTintColor:(UIColor *)color {
    // This method is designed for use with template images, i.e. solid-coloured mask-like images.
    return [self imageWithTintColor:color alpha:0.0]; // default to a fully tinted mask of the image.
}

- (UIImage *)imageWithTintColor:(UIColor *)color alpha:(CGFloat)alpha {
    if (color) {
        // Construct new image the same size as this one.
        UIImage *image;

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
        if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
            UIGraphicsBeginImageContextWithOptions([self size], NO, 0.f); // 0.f for scale means "scale for device's main screen".
        } else {
            UIGraphicsBeginImageContext([self size]);
        }
#else
        UIGraphicsBeginImageContext([self size]);
#endif
        CGRect rect = CGRectZero;
        rect.size = [self size];

        // Composite tint color at its own opacity.
        [color set];
        UIRectFill(rect);

        // Mask tint color-swatch to this image's opaque mask.
        // We want behaviour like NSCompositeDestinationIn on Mac OS X.
        [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0];

        // Finally, composite this image over the tinted mask at desired opacity.
        if (alpha > 0.0) {
            // We want behaviour like NSCompositeSourceOver on Mac OS X.
            [self drawInRect:rect blendMode:kCGBlendModeSourceAtop alpha:alpha];
        }
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return image;
    }

    return self;
}
#pragma clang diagnostic pop
- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha {

    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//等比例缩放
- (UIImage *)scaleToSize:(CGSize)size {
    //不用CGImageGetHeight(self.CGImage)，图片拍摄后会旋转90度，exif属性会记录，CGImageGetHeight实际会获得宽度而不是高度
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    
    float verticalRadio = size.height * 1.0 / height;
    float horizontalRadio = size.width * 1.0 / width;
    
    float radio;
    if (verticalRadio > 1 && horizontalRadio > 1) {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    } else {
        radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width * radio;
    height = height * radio;
    
    int xPos = (size.width - width) / 2;
    int yPos = (size.height - height) / 2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    
    // 绘制改变大小的图片
    [self drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

/**
 *    按照尺寸缩放图片
 *    @param size CGSize
 */
- (UIImage *)shrinkImageForSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (UIImage *)addWaterImage:(UIImage *)waterImage inRect:(CGRect)rect {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
        // 0.0 for scale means "scale for device's main screen".
        UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0);
    }
#else
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0) {
        UIGraphicsBeginImageContext([self size]);
    }
#endif
    //原图
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    //水印图
    [waterImage drawInRect:rect];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}

/**
 * 将图片压缩至 bytes 大小（如果图片本身大小 > bytes  ）
 */
- (UIImage *)shrinkImageForBytes:(NSUInteger)bytes {
    NSData *ret = UIImagePNGRepresentation(self);
    if (ret.length > bytes) {
        float salce = 0.75;
        float maxSize = 125 / salce;
        
        while (ret.length > bytes) {
            maxSize = maxSize * salce;
            ret = UIImagePNGRepresentation([self scaleToSize:CGSizeMake(maxSize, maxSize)]);
        }
    }
    return [UIImage imageWithData:ret];
}

- (UIImage *)addWaterText:(NSString *)text attributes:(NSDictionary*)attributes rect:(CGRect)rect {
    
    CGFloat height = self.size.height;
    CGFloat width = self.size.width;
    //开启一个图形上下文
    UIGraphicsBeginImageContext(self.size);
    
    //在图片上下文中绘制图片
    [self drawInRect:CGRectMake(0, 0,width,height)];
    
    //在图片的指定位置绘制文字   -- 7.0以后才有这个方法
    [text drawInRect:rect withAttributes:attributes];
    
    //从图形上下文拿到最终的图片
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭图片上下文
    UIGraphicsEndImageContext();
    
    return newImg;
}

@end

